package com.antilia.infomaresme.form;

import org.apache.wicket.MarkupContainer;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.IModel;
import org.odlabs.wiquery.core.IWiQueryPlugin;
import org.odlabs.wiquery.core.javascript.JsStatement;
import org.wiquery.plugin.jquertytools.JQueryToolsJavaScriptResourceReference;

/**
 * @author Ernesto Reinaldo Barreiro
 *
 */
public class ShinyForm<T> extends Form<T> implements IWiQueryPlugin, IHeaderContributor {

	private static final long serialVersionUID = 1L;

	ShinyFormVisitor shinyVisitor;
	
	/**
	 * If validation messages should be show as tooltips.
	 */
	private boolean validationMessage = true;
	
	/**
	 * If form filed should be highlighted.
	 */
	private boolean errorHighlightBehavior = true;
	
	/**
	 * Want help tooltips to be shown?
	 */
	private boolean wantHelpTooltips = false;
	
	
	/**
	 * Constructor.
	 * 
	 * @param id
	 */
	public ShinyForm(String id) {
		super(id);
		setOutputMarkupId(true);
	}
	
	/**
	 * Constructor.
	 * 
	 * @param id
	 * @param model
	 */
	public ShinyForm(final String id, IModel<T> model) {
		super(id, model);
		setOutputMarkupId(true);
	}

	
	public void renderHead(IHeaderResponse response) {
		response.renderJavaScriptReference(JQueryToolsJavaScriptResourceReference.get());
	}
	
	public JsStatement statement() {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	protected void onBeforeRender() {
		visitComponents(this);
		super.onBeforeRender();
	}
	
	public static void visitComponent(MarkupContainer component) {
		ShinyForm<?> shinyForm = component.findParent(ShinyForm.class);
		if(shinyForm != null) {
			shinyForm.visitComponents(component);
		}
	}
	
	public void visitComponents(MarkupContainer component) {
		if(shinyVisitor == null) {
			shinyVisitor = new ShinyFormVisitor(wantHelpTooltips, errorHighlightBehavior, validationMessage);
		}
		component.visitChildren(shinyVisitor);
		shinyVisitor.clearVisited();
	}

	public void setShinyVisitor(ShinyFormVisitor shinyVisitor) {
		this.shinyVisitor = shinyVisitor;
	}

	public boolean isValidationMessage() {
		return validationMessage;
	}

	public ShinyForm<T> setValidationMessage(boolean validationMessage) {
		this.validationMessage = validationMessage;
		return this;
	}

	public boolean isErrorHighlightBehavior() {
		return errorHighlightBehavior;
	}

	public ShinyForm<T> setErrorHighlightBehavior(boolean errorHighlightBehavior) {
		this.errorHighlightBehavior = errorHighlightBehavior;
		return this;
	}

	public boolean isWantHelpTooltips() {
		return wantHelpTooltips;
	}

	public ShinyForm<T> setWantHelpTooltips(boolean wantHelpTooltips) {
		this.wantHelpTooltips = wantHelpTooltips;
		return this;
	}
	
}
